package com.biovr.backend.restcontroller;

import com.biovr.backend.config.ErrorCode;
import com.biovr.backend.utils.QiniuUtils;
import com.biovr.backend.utils.ResponseFactory;
import com.biovr.backend.utils.RestResponse;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * Created by jnmcl on 2017/7/7.
 */
@RestController
@RequestMapping("/files")
public class ServerFileRestController {
  @Autowired
  QiniuUtils qiniuUtils;

  @GetMapping
  public RestResponse<FileInfo[]> listAllFiles(){
    FileInfo[] info = qiniuUtils.listAllFiles();
    return ResponseFactory.createSuccessResult(info);
  }
  @GetMapping("/auth")
  public RestResponse<String> uploadAuth(@RequestParam (required = false) String key, @RequestParam (required = false) String expire){

    String auth="";
    boolean keyIsNull = (key==null || key=="");
    boolean forever = expire==null || expire=="";
    if (keyIsNull && forever){
      auth = qiniuUtils.getUpToken();
    }
    else if (keyIsNull && !forever){
      auth= qiniuUtils.getUpToken( Long.parseLong(expire));
    }
    else if (!keyIsNull && forever){
      auth = qiniuUtils.getUpToken(key);
    }
    else if ( !keyIsNull && !forever){
      auth = qiniuUtils.getUpToken(key, Long.parseLong(expire));
    }
    return ResponseFactory.createSuccessResult(auth);
  }
  @DeleteMapping("/{key}")
  public RestResponse<String> deleteFile(@PathVariable String key){
    //构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(Zone.zone0());
//...其他参数参考类注释

    String accessKey = qiniuUtils.getAccessKey();
    String secretKey = qiniuUtils.getSecretKey();

    String bucket = qiniuUtils.getBucket();

    Auth auth = Auth.create(accessKey, secretKey);
    BucketManager bucketManager = new BucketManager(auth, cfg);
    try {
      bucketManager.delete(bucket, key);
      return ResponseFactory.createSuccessResult();
    } catch (QiniuException ex) {
      //如果遇到异常，说明删除失败
      return ResponseFactory.createErrorResult(ex.error());
    }

  }
}
